<template>
  <div id="videoPlay_box">
    <div
      id="video-wrap-player"
      v-if="mediaUri"

    >
      <video-player
        id="videoPlayer"
        class="video-player vjs-custom-skin"
        ref="videoPlayer"
        :options="playerOptions"
        :playsinline="playsinline"
        @ready="onPlayerReady($event)"
        @play="onPlayerPlay($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @loadeddata="onPlayerLoadeddata($event)"
        @pause="onPlayerPause($event)"
        @ended="onPlayerEnded($event)"

      >

      </video-player>
    </div>
  </div>
</template>

<style src="./index.less" lang="less" scoped></style>

<script>
import { updateCourseLearning, getCourseLessonsDetail } from '@/api/course'
import watermark from '@/assets/js/watermark'
export default {
  name: 'videoboPlayer',
  props: ['courseId', 'coursewareId', 'isDrag', 'doubleSpeed', 'from'],
  components: {},
  data() {
    return {
      stageId: this.$route.query.stageId, // 阶段ID
      trainId: this.$route.query.trainId, // 培训ID
      mediaUri: '', // 视频url
      isPaused: '', // 视频暂停
      currentTime: 0, // 学习课程时间；
      TimingUpdateProgress: {}, // 定时更新进度计时器
      canDrag: false, // 是否可拖动
      nowCurrentTime: '', // 视频当前学习位置
      videoTotalLength: 0, // 视频总长度
      player: null,
      isEnded: false, // 是否触发视频end事件
      isUpdateing: false, // 更新课件进度接口请求中
      waterText: '', // 水印文字
      learnProgress: 0, // 学习进度
      nextCourseware: {}, // 下一节课程信息
      lessonInfo: {},
      setTimer: null,
      cutScreenCatchTime: 0, // 记录切屏时间
      isCutScreen: false, // 是否存在切屏
      sourceId: '',
      isStart: false,
      playerOptions: {},
      isIOS: false,
      isLandscape: false // 是否旋转屏幕
    }
  },
  computed: {
    playsinline() {
      var ua = navigator.userAgent.toLocaleLowerCase()
      if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        return false
      } else {
        return true
      }
    }
  },
  watch: {
    coursewareId: {
      handler(val) {
        clearTimeout(this.setTimer)
        clearInterval(this.TimingUpdateProgress)
        this.setTimer = null
        this.TimingUpdateProgress = null
        this.setTimer = setTimeout(() => {
          this.$router.go(0)
        }, 240)
      },
      deep: true,
      immediate: false
    },

    // 暂停状态变更，更新进度
    isPaused(val) {
      if (val) {
        this.updateLearningTime(this.currentTime)
      }
    }
  },
  mounted() {
    const userAgent = window.navigator.userAgent.toLowerCase()
    this.isIOS = /iphone|ipad|ipod/.test(userAgent)
    console.log('是否是iOS端', this.isIOS)
    this.waterText = window.localStorage.getItem('companyName')
    if (this.from == 'train') {
      this.sourceId = this.$route.query.trainId
    } else {
      this.sourceId = this.courseId
    }
    console.log(this.lessonData)
    this.getLessonDetail()
    window.addEventListener('beforeunload', () => {
      this.updateLearningTime(this.currentTime)
    })
  },
  beforeDestroy() {
    clearInterval(this.TimingUpdateProgress)
    document.removeEventListener('pause', this.listeningExit, false)
    document.removeEventListener('resume', this.listeningEntry, false)
    window.removeEventListener('beforeunload', () => {
      this.updateLearningTime(this.currentTime)
    })
    this.updateLearningTime(this.currentTime)
  },
  methods: {

    onPlayerReady(player) {
      let _self = this
      console.log('Player is ready!', player)

      // 判断ios
      let ua = navigator.userAgent.toLowerCase()
      // 判断ios的版本号
      let ver = ua.match(/cpu iphone os (.*?) like mac os/)
      if (!ver || parseInt(ver[1] < 11)) {
        // fastclick冲突问题
        $('.vjs-control-bar').children().addClass('needsclick')
      }

      if (_self.isDrag == 'close' && !_self.canDrag) {
        // 禁止拖动
        document.querySelector('.vjs-progress-control').style.pointerEvents = 'none'

        console.log('禁止拖动')
      } else {
        // 可以拖动
        document.querySelector('.vjs-progress-control').style.pointerEvents = 'auto'
        console.log('可以拖动')
      }
      if (_self.isIOS) {
        player.currentTime(0)
      } else {
        // 设置初始播放位置
        player.currentTime(_self.currentTime)
      }
      if (this.waterText) {
        watermark({
          watermark_id: 'videoPlay_box',
          watermark_txt: this.waterText,
          watermark_fontsize: '14px',
          watermark_x: 0,
          watermark_x_space: 30,
          watermark_width: 140,
          watermark_cols: 5
        })
      }
    },
    onPlayerPlay(player) {
      console.log('开始播放')
      // 设置初始播放位置
      player.currentTime(this.currentTime)
      this.isPaused = false
      this.isEnded = false

      // 定时同步进度（30s一次）
      this.TimingUpdateProgress = setInterval(() => {
        this.updateLearningTime(this.currentTime)
      }, 30000)
    },
    onPlayerTimeupdate(player) {
      // console.log('播放中', this.nowCurrentTime)

      // 当不允许拖动，课程未完成时，存在切到后台,不往下执行
      if (this.checkBackCutScreen()) {
        return
      }

      this.nowCurrentTime = player.currentTime().toFixed(2)
      this.currentTime = this.nowCurrentTime

      // 暂停时传递进度
      if (this.isPaused) {
        this.currentTime = this.nowCurrentTime
      }
    },
    onPlayerLoadeddata(player) {
      // player.currentTime(this.currentTime)
    },
    onPlayerPause(player) {
      console.log('暂停播放')
      // 防止拖动产生的pause事件重复发送请求
      if (!this.isPaused) {
        clearInterval(this.TimingUpdateProgress)
        this.currentTime = player.currentTime().toFixed(2)
        this.isPaused = true
      }
    },
    onPlayerEnded(player) {
      // 当不允许拖动，课程未完成时，存在切到后台,不往下执行
      if (this.checkBackCutScreen()) {
        return
      }

      // 添加isEnded判断，防止重复
      if (this.isEnded) {
        return
      }
      // 结束播放时自动推出全屏
      if (player.isFullscreen()) {
        player.exitFullscreen()
      }

      clearInterval(this.TimingUpdateProgress)

      // 播放完毕，设置进度条拖动状态
      this.canDrag = true
      this.isEnded = true
      this.isPaused = true
    },
    // 视频 end

    getLessonDetail() {
      let _self = this
      getCourseLessonsDetail(this.coursewareId, {
        from: this.from,
        sourceId: this.sourceId,
        courseId: this.courseId,
        stageId: this.stageId ? this.stageId : this.courseId
      }).then(res => {
        this.lessonData = res.data
        console.log(this.lessonData)
        // 下节课件
        this.nextCourseware = this.lessonData.nextCourseware ? this.lessonData.nextCourseware : {}
        if (this.nextCourseware.uuid) {
          this.lessonInfo = {
            title: this.nextCourseware.title,
            courseId: this.nextCourseware.courseId,
            uuid: this.nextCourseware.uuid,
            coursewareType: this.nextCourseware.type
          }
        } else {
          this.lessonInfo = {
            uuid: ''
          }
        }
        if (Number(_self.lessonData.convertStatus) === 1) {
          _self.learnProgress = _self.lessonData.progress
          let currentTime = _self.lessonData.progressBar ? _self.lessonData.progressBar : 0 // 当前学习位置
          _self.currentTime = Number(currentTime)
          _self.videoTotalLength = Number(_self.lessonData.length)

          if (_self.learnProgress == '100') {
            _self.canDrag = true
            if (Number(_self.currentTime) >= Number(_self.videoTotalLength)) {
              // 如果已完成，且当前位置大于总时长，定位到0
              _self.currentTime = 0
            }
          } else {
            _self.canDrag = false
          }

          _self.currentTime = Math.round(_self.currentTime)

          let playbackRates = []
          if (_self.doubleSpeed == 'open') {
            // 开启倍速
            playbackRates = [0.5, 1.0, 1.5, 2.0]
          } else {
            // 不开启倍速
            playbackRates = []
          }

          _self.playerOptions = {
            //视频url设置,直播流为例
            sources: [
              {
                src: _self.lessonData.transCodeUri, //视频文件地址
                type: 'application/x-mpegURL' //视频类型，这里可以不写，如果写一定要写对，否则会无法播放
              }
            ],
            playbackRates: playbackRates,
            fluid: true,
            autoplay: false,
            muted: false,
            controls: true,

          }
          _self.mediaUri = _self.lessonData.transCodeUri

          // 监听退到后台，唤醒
          document.addEventListener('pause', _self.listeningExit, false)

          document.addEventListener('resume', _self.listeningEntry, false)
        } else {
          this.$dialog.alert({
            title: '温馨提示',
            message: '视频文件正在转换中，稍后完成后即可查看'
          })
        }
      })
    },

    /**
     * 更新课件播放时间公共方法
     * @param {number} nowPlayTime 当前播放的时间
     */
    updateLearningTime(nowPlayTime) {
      let _self = this
      if (this.isUpdateing) {
        return false
      }
      _self.isUpdateing = true
      updateCourseLearning({
        coursewareId: _self.coursewareId,
        progressBar: Number(nowPlayTime).toFixed(2),
        from: _self.from,
        sourceId: _self.sourceId,
        courseId: _self.courseId,
        stageId: _self.stageId ? _self.stageId : _self.courseId
      })
        .then(res => {
          setTimeout(() => {
            _self.isUpdateing = false
          }, 1000)
          if (res.data.progress == '100' && res.data.open) {
            // 完成
            _self.$emit('nextLessonPlay', _self.lessonInfo)
          }
        })
        .catch(err => {
          this.isUpdateing = false
        })
    },

    // 校验是否是切到后台，调整视频进度
    checkBackCutScreen() {
      // 当不允许拖动，课程未完成时，存在切到后台
      if (this.isCutScreen && this.isDrag == 'close' && !this.canDrag) {
        return true
      }
    },
    // 监听退到后台
    listeningExit() {
      // 是否存在切屏标识
      this.isCutScreen = true

      // 记录当前切屏到退出后台的时间
      this.cutScreenCatchTime = this.$refs.videoPlayer.player?.currentTime()

      console.log('退出后台时间：' + this.cutScreenCatchTime)

      this.$refs.videoPlayer.player && this.$refs.videoPlayer.player.pause()
    },
    // 监听唤醒
    listeningEntry() {
      this.$nextTick(() => {
        // 是否存在切屏标识
        this.isCutScreen = false
        let _currentTime = this.$refs.videoPlayer.player?.currentTime()

        // 当不允许拖动，课程未完成时，允许后退，不允许前进
        if (_currentTime > this.cutScreenCatchTime && this.isDrag == 'close' && !this.canDrag) {
          _currentTime = this.cutScreenCatchTime
        }

        this.$refs.videoPlayer.player && this.$refs.videoPlayer.player?.currentTime(_currentTime - 0.1)
        this.$refs.videoPlayer.player && this.$refs.videoPlayer.player.play()
      })
    }
  }
}
</script>

<style lang="less">
.vjs-watermark {
  color: #fff;
  text-shadow: #000 2px 2px 2px;
  letter-spacing: 3px;
  position: relative;
  width: 200px;
  display: block;
  padding-left: 40px;
  box-sizing: border-box;
  text-align: center;
  white-space: nowrap;
  line-height: 30px;

  img {
    width: 30px;
    height: 30px;
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
